package liwen.zhao.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import liwen.zhao.common.jd.pojo.Article;
import liwen.zhao.common.jd.vo.SysResult;
import liwen.zhao.mappers.ArticleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    SysResult sysResult;
    @Autowired(required = false)
    ArticleMapper articleMapper;
    @Autowired
    StringRedisTemplate redisTemplate;
    
    @Value("${pageSize}")
    private int pageSize;
    
    ObjectMapper objectMapper=new ObjectMapper();
    @Override
    public SysResult addArticle(Article article) {
        Long time=System.currentTimeMillis()/1000;
        article.setContent("");
        article.setCtime(time);
        article.setUtime(time);
        try {
            articleMapper.addArticle(article);
            //对信息进行缓存
            if(article.getIfCache()==1){
                String articleJson = objectMapper.writeValueAsString(article);
                redisTemplate.opsForValue().set("shopId" + article.getId(),articleJson);
            }
            return SysResult.ok();
        }catch (Exception e){
            e.printStackTrace();
            return sysResult;
        }
    }
    
    @Override
    public SysResult getArticleById(String id) {
        try {
            String shopJson=redisTemplate.opsForValue().get("shopId" + id);
            Article article;
            if(null!=shopJson){//如果缓存中有数据，直接从缓存中读取
                article = objectMapper.readValue(shopJson, Article.class);
            }else{
                article=articleMapper.getArticleById(id);
            }
            sysResult.setStatus(200);
            sysResult.setData(article);
            return sysResult;
        }catch (Exception e){
            sysResult.setStatus(500);
            return sysResult;
        }
    }
    
    @Override
    public SysResult getArticleList(int page) {
        try {
            List<Article> articleList=articleMapper.selectArticleByPage((page-1)*pageSize,pageSize);
            sysResult.setStatus(200);
            sysResult.setData(articleList);
        } catch (Exception e) {
            e.printStackTrace();
            sysResult.setStatus(500);
            return sysResult;
        }
        return sysResult;
    }
}
